import copy

from appserver import db_store


class Area(db_store.Model):
    __tablename__ = "area"
    __bind_key__ = "main"

    area_id = db_store.Column(db_store.VARCHAR(38), primary_key=True, comment=u'区域编号')
    name = db_store.Column(db_store.VARCHAR(50), nullable=False, comment=u'区域名称')
    code = db_store.Column(db_store.VARCHAR(38), nullable=False, comment=u'区域编码')
    level = db_store.Column(db_store.Integer, nullable=False, comment=u'区域等级')
    parent_id = db_store.Column(db_store.VARCHAR(38), comment=u'父ID')
    wbs = db_store.Column(db_store.VARCHAR(38), comment=u'wbs编码')
    center = db_store.Column(db_store.VARCHAR(50), comment=u'中心点')
    polyline = db_store.Column(db_store.TEXT, comment=u'区域边界')

    def __repr__(self):
        return '<Area %r>' % self.name

    @staticmethod
    def get_area_all():
        return Area.query.all()

    @staticmethod
    def get_areas_by_level(level):
        return Area.query.filter_by(level=level).all()

    @staticmethod
    def get_areas_by_parent_id(parent_id):
        return Area.query.filter_by(parent_id=parent_id).all()

    def from_dict(self, rev_source):
        # 深拷贝一下,获取一个新的字典,防止遍历时出错
        source = copy.deepcopy(rev_source)
        for k in source:
            try:
                getattr(self, k)
                # print(444, getattr(self, k))
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])
    # 返回字典,key是c.name ,值是 字段的值, 返回给前端时调用
    def to_dict(self):
        return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}

    # def get_max_id(self):
    #     val = db_store.session.query(func.max(self.__class__.id)).scalar()
    #     if not val:
    #         return 0
    #     else:
    #         return val

    def save(self):
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def get_entity_by_id(self, id):
        return copy.deepcopy(self.query.filter_by(id=id).first())

    def get_list_all(self):
        return self.query.all()


